package com.heima.comment.service.impl;

import com.heima.apis.article.IArticleClient;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.comment.dao.CommentRepository;
import com.heima.comment.dao.LikeRepository;
import com.heima.comment.service.ICommentService;
import com.heima.comment.util.ApTokenThreadLocalUtil;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.Comment;
import com.heima.model.comment.pojos.Like;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service
public class CommentServiceImpl implements ICommentService {

    @Resource
    private CommentRepository commentRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private LikeRepository likeRepository;

    @Resource
    private IWemediaClient wemediaClient;

    @Resource
    private IArticleClient articleClient;


    /**
     * 保存用户评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        long articleId = dto.getArticleId();
        ApArticle article = articleClient.getArticleById(articleId);
        log.info(article.toString());
        if (article == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        String content = dto.getContent();
        System.out.println("content = " + content);


        try {
            wemediaClient.commentInspect(content);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.RUBBISH_COMMENT);
        }

        Comment comment = new Comment();
        comment.setAuthorId(article.getAuthorId());//被评论人，文章作者ID
        comment.setUserId(user.getId());//评论人
        comment.setArticleId(articleId);//文章ID
        comment.setLikeNum(0);//点赞数
        comment.setPublishTime(new Date());//评论时间
        comment.setParentId("0");//0表示直接属于文章一级评论
        comment.setReplyNum(0);//该评论回复数
        comment.setContent(content);//评论内容

        try {
            commentRepository.save(comment);
        } catch (Exception e) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

        return ResponseResult.okResult(null);
    }

    /**
     * 查询评论列表，文章一级评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadComment(CommentDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        long articleId = dto.getArticleId();
        Date minDate = dto.getMinDate();
        Date date = new Date();
        System.out.println(minDate.after(date));

        Query query = Query.query(Criteria.where("publishTime")
                        .lt(minDate)
                        .and("articleId").is(articleId)
                        .and("parentId").is("0")
                )
                .with(Sort.by(Sort.Direction.DESC, "publishTime"))
                .with(PageRequest.of(0, 10));
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);
        System.out.println(commentList);

        //获取文章信息
        ApArticle article = articleClient.getArticleById(articleId);
        if (article == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        /**
         * 评论内容，评论作者，点赞数，回复数，时间，operation，
         */
        List<Map<String, Object>> vos = new ArrayList();
        for (Comment comment : commentList) {
            Map<String, Object> vo = new HashMap<>();
            vo.put("id", comment.getId());
            vo.put("authorId", comment.getAuthorId());
            vo.put("authorName", article.getAuthorName());
            vo.put("entryId", article.getId());
            vo.put("channelId", null);
            vo.put("type", article.getId());
            vo.put("content", comment.getContent());
            vo.put("image", article.getImages());
            vo.put("likes", comment.getLikeNum());
            vo.put("reply", comment.getReplyNum());
            vo.put("flag", article.getFlag());
            vo.put("logitude", null);
            vo.put("latitude", null);
            vo.put("address", null);
            vo.put("ord", null);
            vo.put("createdTime", comment.getPublishTime());
            vo.put("updatedTime", null);
            Like like = likeRepository.findByUserIdAndCommentId(user.getId(), comment.getId());
            if (like != null) {
                vo.put("operation", 0);
            }
            vos.add(vo);
        }
        return ResponseResult.okResult(vos);
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeComment(CommentLikeDto dto) {
        ApUser user = ApTokenThreadLocalUtil.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String commentId = dto.getCommentId();
        short operation = dto.getOperation();

        //判断是否点赞
        Like like = likeRepository.findByUserIdAndCommentId(user.getId(), dto.getCommentId());
        if (operation == 0 && like != null) {
            //是点赞操作且已经点过赞
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已点赞");
        }

        Comment comment = commentRepository.findById(commentId).get();
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (operation == 0) {
            //点赞操作
            like = new Like();
            like.setCommentId(commentId);
            like.setUserId(user.getId());
            likeRepository.save(like);
            //点赞数加一
            comment.setLikeNum(comment.getLikeNum() + 1);
        } else {
            //取消点赞
            likeRepository.delete(like);
            //点赞数减一
            comment.setLikeNum(comment.getLikeNum() - 1);
        }
        commentRepository.save(comment);

        Map<String, Object> vo = new HashMap<>();
        vo.put("likes", comment.getLikeNum());
        return ResponseResult.okResult(vo);
    }
}
